package cn.tedu.blackhorse.service.impl;

import cn.tedu.blackhorse.ex.ServiceCode;
import cn.tedu.blackhorse.ex.ServiceException;
import cn.tedu.blackhorse.mapper.CourseMapper;
import cn.tedu.blackhorse.pojo.dto.CourseAddNewDTO;
import cn.tedu.blackhorse.pojo.dto.CourseUpdateDTO;
import cn.tedu.blackhorse.pojo.entity.Course;
import cn.tedu.blackhorse.pojo.vo.CourseListItemVO;
import cn.tedu.blackhorse.pojo.vo.CourseStandardVO;
import cn.tedu.blackhorse.service.ICourseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Slf4j
@Service
public class CourseServiceImpl implements ICourseService {
    @Autowired
     CourseMapper mapper;

    @Override
    public void addNew(CourseAddNewDTO courseAddNewDTO) {
      int count =  mapper.countByName(courseAddNewDTO.getCourse());
      if (count != 0){
          String message = "添加失败,课程名称失败!";
          log.debug(message);
          throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
      }
        Course course = new Course();
        BeanUtils.copyProperties(courseAddNewDTO,course);
        int rows = mapper.insert(course);
        if (rows != 1){
            String message = "添加失败,系统繁忙,请稍后再试!";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
    }

    @Override
    public void deleteById(Long id) {
        CourseStandardVO courseStandardVO = mapper.getById(id);
        if (courseStandardVO==null){
            String message = "删除失败,删除的课程未找到";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        int row = mapper.deleteById(id);
        if (row != 1){
            String message = "删除失败,系统繁忙,请稍后再试!";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
    }

    @Override
    public void update(Long id, CourseUpdateDTO courseUpdateDTO) {
        CourseStandardVO courseStandardVO = mapper.getById(id);
        if (courseStandardVO == null){
            String message = "修改失败,课程未找到";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        int row = mapper.updateById(courseUpdateDTO);
        if (row != 1){
            String message = "修改失败,系统繁忙,请稍后重试";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
    }

    @Override
    public List<CourseListItemVO> list() {
        return mapper.list();
    }
}
